import time
import sys
import struct, fcntl, signal, socket, select
import os
import getpass
import django
import paramiko
from paramiko.ssh_exception import SSHException


os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'website.settings')
django.setup()
from django.db.models import Q
from django.conf import settings
from asset.models import Host
from django.contrib.auth import get_user_model
Users = get_user_model()

try:
    import termios
    import tty
except ImportError:
    print('\033[1;31m仅支持类Unix系统 Only unix like supported.\033[0m')
    time.sleep(3)
    sys.exit()

def print_green(cont):
        print('\033[1;32;40m%s\033[0m' % cont)

def print_red(cont):
        print('\033[1;31;40m%s\033[0m' % cont)

def print_yellow(cont):
        print('\033[1;33;40m%s\033[0m' % cont)

def print_blue(cont):
        print('\033[1;34;40m%s\033[0m' % cont)

def signal_handler(signal,frame):
    print()
    print_green('You pressed Ctrl+C!,Please pressed "Enter" continue')

class SSHConnection():
    """
    SSH连接类
    """
    def __init__(self,conndict):
        self.host = conndict["hostip"]
        self.port = conndict["sshport"]
        self.nkey = conndict["sshkeyfile"]
        self.username = conndict["sshuser"]
        self.timeout = 60
        self.connect_key()


    def connect_key(self):
        try:
            self.private_key = paramiko.RSAKey.from_private_key_file(self.nkey)
            self.sshclient = paramiko.SSHClient()
            self.sshclient.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            self.sshclient.connect(hostname=self.host, port=self.port, username=self.username, pkey=self.private_key, allow_agent=False, look_for_keys=False)

        except SSHException as ssh:
            error_msg = "SSH连接失败：{}，请检查重试！".format(str(ssh))
            print_red(error_msg)

    @staticmethod
    def get_win_size():
        """
        This function use to get the size of the windows!
        获得terminal窗口大小
        """
        width = os.get_terminal_size().columns

        height = os.get_terminal_size().lines
        return width,height

    def set_win_size(self, sig, data):
        """
        This function use to set the window size of the terminal!
        设置terminal窗口大小
        """
        try:

            width,height = self.get_win_size()
            self.channel.resize_pty(height=height, width=width)
        except Exception:
            pass

    def connect_server(self):
        login_msg = "clear;echo -e '\\033[32m登录服务器 %s 成功. 感谢使用腾展跳板机系统!.\\033[0m'\n" % self.host
        transport = self.sshclient.get_transport()
        # transport.set_keepalive(30)
        # transport.use_compression(True)
        self.channel = transport.open_session()
        width, height = self.get_win_size()
        self.channel.get_pty(term='xterm', width=width, height=height)
        self.channel.invoke_shell()
        try:
            signal.signal(signal.SIGWINCH, self.set_win_size)
        except:
            pass
        self.channel.send(login_msg)
        self.jms_shell(self.channel)
        self.channel.close()
        self.sshclient.close()

    def jms_shell(self,chan):
        old_tty = termios.tcgetattr(sys.stdin)
        try:
            tty.setraw(sys.stdin.fileno())
            tty.setcbreak(sys.stdin.fileno())
            self.channel.settimeout(0.0)
            while True:
                try:
                    r, w, e = select.select([chan, sys.stdin], [], [])
                except:
                    pass

                if chan in r:
                    try:
                        x = chan.recv(10240).decode('utf-8', 'ignore')
                        if len(x) == 0:
                            break
                        sys.stdout.write(x)
                        sys.stdout.flush()
                    except socket.timeout:
                        pass

                if sys.stdin in r:
                    x = os.read(sys.stdin.fileno(), 1)
                    if len(x) == 0:
                        break
                    chan.send(x)
        finally:
            termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_tty)





# class DjangoSomething(object):

#     def __init__(self,user):
#         self.user = user

#     def check_user(self):
#         try:
#             Users.objects.get(name=self.user)
#         except:
#             print_red('跳板机对此用户不支持,请确认是否以 root 用户启动,或者查看CMDB是否有此用户')
#             print_green('按任意键退出系统......')
#             input('\033[1;31m>\033[0m')
#             sys.exit()

#     def get_hosts(self):
#         self.userinfo = Users.objects.get(name=self.user)
#         # user_role = Role.objects.filter(userrelationrole__user_info_id__name=self.user)
#         host_query_list = Host.objects.filter(id=0)
#         # for ur in user_role:
#         #     if ur.name == 'super' or ur.name == 'admin' or ur.name == 'cmdbAdmin' or ur.name == 'cmdbreader':
        
#         hosts = Host.objects.all().order_by('id')
#         return ip_list

#     def search_host(self,option):
#         self.get_hosts()
#         try:
#             search_queryset = self.host_query_list.filter(Q(name__icontains=option)|Q(public_ip__icontains=option))
#             if len(search_queryset) > 1:
#                 host_list = []
#                 for host in search_queryset:
#                     host_str = '>   [name: {}]  [ipaddress: {}]  [description: {}]'.format(host.name, host.public_ip, host.description)
#                     host_list.append(host_str)
#                 return False,host_list
#             elif len(search_queryset) == 1 and len(search_queryset) > 0:
#                 host_dict = {
#                     'hostip': search_queryset[0].public_ip,
#                     'sshport': search_queryset[0].connect_port,
#                     'sshkeyfile': os.path.join('/opt/.keys',search_queryset[0].sshkey_id.name),
#                     'sshuser': search_queryset[0].sshkey_id.ssh_user,
#                 }
#                 return True,host_dict
#             else:
#                 print_red("获取主机失败,请检查输入.......[ {} ]".format(option))
#         except Exception as e:
#             print_red("获取主机失败[{}],请检查输入.......[ {} ]".format(str(e),option))

# def opt_option(option):
#     if option in ['exit', 'q', 'Q']:
#         sys.exit()
#     elif option in ['P', 'p']:
#         ip_list = ds.get_hosts()
#         # os.system('clear')
#         print_yellow('你具有权限的主机[前10]')
#         for ip in ip_list[:10]:
#             print_blue(ip)
#         print_green('1).输入 IP或者主机名 登录主机')
#         print_green('2).输入 Q/exit 退出系统')
#         option = input("\033[1;32mOperation Input>:\033[0m ").strip()
#         opt_option(option)
#     elif option in ['G', 'g']:
#         print_red("目前还不支持此功能......")

#     elif option in ['H', 'h']:
#         print_red("目前还不支持此功能......")

#     else:
#         try:
#             status, result = ds.search_host(option)
#             if status:
#                 print_blue("连接服务器中,请稍等......")
#                 time.sleep(1)
#                 ssh = SSHConnection(result)
#                 ssh.connect_server()


#             else:
#                 os.system('clear')
#                 print_yellow('查询到的主机[前10]')
#                 for ip in result[:10]:
#                     print_blue(ip)
#                 print_green('1).输入 IP或者主机名 登录主机')
#                 print_green('2).输入 Q/exit 退出系统')
#                 option = input("\033[1;32mOperation Input>:\033[0m ").strip()
#                 opt_option(option)
#         except Exception as e:
#             print_red(e)


# def tzjmsmain():
#     while True:
#         print_blue('#'*50)
#         print_yellow('======    欢迎使用腾展跳板机系统    ======')
#         print_green('1).输入 P/p 显示具有权限的主机')
#         print_green('2).输入 G/g 显示具有权限的主机组')
#         print_green('3).输入 IP或者主机名 登录主机')
#         print_green('4).输入 H/h 帮助')
#         print_green('5).输入 Q/exit 退出系统')
#         print_blue('#' * 50)
#         signal.signal(signal.SIGINT, signal_handler)
#         try:
#             option = input("\033[1;32mOperation Input>:\033[0m ").strip()
#         except EOFError:
#             sys.exit()
#         opt_option(option)


if __name__ == '__main__':
    user_name = getpass.getuser()
    # ds = DjangoSomething(user_name)
    # ds.check_user()
    # tzjmsmain()